#pragma once
#include "../comm/logger.hpp"
#include "../comm/util.hpp"
#include <unordered_map>
#include <cassert>
#include <mysql/mysql.h>
namespace ns_model
{
    using namespace std;
    using namespace ns_util;
    struct Question
    {
        std::string number; // 题目编号，唯一
        std::string title;  // 题目的标题
        std::string star;   // 难度: 简单 中等 困难
        int cpu_limit;      // 题目的时间要求(S)
        int mem_limit;      // 题目的空间要去(KB)
        std::string desc;   // 题目的描述
        std::string header; // 题目预设给用户在线编辑器的代码
        std::string tail;   // 题目的测试用例，需要和header拼接，形成完整代码
    };

    const std::string oj_questions = "oj_questions";
    const std::string host = "127.0.0.1";
    const std::string user = "oj_usr";
    const std::string passwd = "123456";
    const std::string db = "oj";
    const int port = 3306;

    class Model
    {
    public:
        Model()
        {
        }
        ~Model() {}

        bool QueryMySql(const std::string &sql, std::vector<struct Question> *out)
        {
            MYSQL *my = mysql_init(nullptr);

            // 连接数据库
            if (nullptr == mysql_real_connect(my, host.c_str(), user.c_str(), passwd.c_str(), db.c_str(), port, nullptr, 0))
            {
                LOG(FATAL, "数据库连接失败\n");
                return false;
            }

            // 设置编码格式
            mysql_set_character_set(my, "utf8");

            // 执行语句
            if (0 != mysql_query(my, sql.c_str()))
            {
                LOG(FATAL, "执行mysql语句错误\n");
                return false;
            }

            // 获取结果
            MYSQL_RES *res = mysql_store_result(my);
            int rows = mysql_num_rows(res);

            Question q;

            for (int i = 0; i < rows; i++)
            {
                MYSQL_ROW row = mysql_fetch_row(res);
                q.number = row[0];
                q.title = row[1];
                q.star = row[2];
                q.desc = row[3];
                q.header = row[4];
                q.tail = row[5];
                q.cpu_limit = atoi(row[6]);
                q.mem_limit = atoi(row[7]);

                out->push_back(q);
            }


            free(res);
            mysql_close(my);
        }

        bool GetAllQuestions(vector<Question> *out)
        {
            // mysql 查找所有question
            std::string sql = "select * from oj_questions";
            return QueryMySql(sql, out);
        }

        bool GetOneQuestion(const std::string &number, Question *q)
        {
            std::string sql = "select * from oj_questions where id = ";
            sql += number;
            vector<struct Question> out;
            if (QueryMySql(sql, &out) && out.size() == 1)
            {
                (*q) = out[0];
                return true;
            }
            LOG(FATAL, "获取所有题目失败\n");
            return false;
        }
    };
}